package com.onpositive.realmview;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;


import com.onpositive.realmview.model.IStreamPersistable;
import com.onpositive.realmview.progress.IProgressMonitor;
import com.onpositive.semantic.model.realm.IModifiableRealm;
import com.onpositive.semantic.model.realm.Realm;

public class NamedObject implements INamedObject, IStreamPersistable {

	protected final IModifiableRealm<? extends NamedObject> parent;

	public NamedObject(IModifiableRealm<? extends NamedObject> parent) {
		super();
		this.parent = parent;
	}

	protected String description = "";
	protected String icon = "";
	protected String name = "";

	public String getDescription() {
		return description;
	}

	public String getIcon() {
		return icon;
	}

	public String getName() {
		return name;
	}

	public boolean isDirty() {
		return false;
	}

	public void save(IProgressMonitor monitor) {
		if (parent!=null){
			((Realm) parent).changed(Collections.singleton(this));
		}
	}

	public void store(DataOutputStream stream) throws IOException {
		stream.writeUTF(name);
		stream.writeUTF(description);
		stream.writeUTF(icon);
	}

	public void read(DataInputStream stream) throws IOException {
		name = stream.readUTF();
		description = stream.readUTF();
		icon = stream.readUTF();
	}

	

	
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		NamedObject other = (NamedObject) obj;
		if (description == null) {
			if (other.description != null)
				return false;
		} else if (!description.equals(other.description))
			return false;
		if (icon == null) {
			if (other.icon != null)
				return false;
		} else if (!icon.equals(other.icon))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public void setDescription(String description) {
		this.description = description;
		save(null);
	}

	public void setIcon(String icon) {
		this.icon = icon;
		save(null);
	}

	public void setName(String name) {
		this.name = name;
		save(null);
	}

	protected void updateFrom(INamedObject original) {
		this.name=original.getName();
		this.description=original.getDescription();
		this.icon=original.getIcon();
	}
}
